package com.itheima.demo;

import java.util.Arrays;

public class demo_001 {
    public static void main(String[] args) {
        int[] arr = {12, 34, 67, 55, 88, 2, 1, 9, 0};
        //首先对数组使用冒泡排序进行排序;
        //外循环控制次数;
        for (int i = 0; i < arr.length - 1; i++) {
            //内循环控制比较次数;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println("排序后的数组为:" + Arrays.toString(arr));
        int number = 55;
        int index = method(arr, number);
        System.out.println("数字["+number+"]所在数组的索引位置是:\t"+index);
    }

    //二分查找方法;
    private static int method(int[] arr, int number) {
        int min = 0;
        int max = arr.length - 1;
        //使用循环进行判断;
        while (min <= max) {
            //求出中间的索引值;
            int mid = min + (max - min) / 2;
            //进行判断;
            if (arr[mid] > number) {
                max = mid - 1;
            } else if (arr[mid] < number) {
                min = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
